package com.bafa.dbcache;

import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.middle.betwixt.Utils;
import com.bafa.objects.Match;
import com.bafa.objects.PageBean;
import com.bafa.objects.player.Player;
import com.bafa.objects.schema.ObjectFactory;
import com.bafa.objects.schema.Score;
import com.bafa.objects.schema.Scorer;
import com.bafa.objects.schema.Team;
import com.bafa.tables.Keys;
import com.wutka.jox.JOXBeanInputStream;
import com.wutka.jox.JOXBeanReader;

import java.io.ByteArrayInputStream;
import java.io.StringReader;

import java.io.StringWriter;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.util.HashMap;
import java.util.TreeMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.commons.betwixt.io.BeanWriter;

//import com.bafa.objects.Match;

public class LeagueCache implements Keys{

	
	//private static TreeMap seasons = new TreeMap();
	//private static TreeSet seasonsOrder = new TreeSet(new SeasonComparator());
	private static TreeMap matches = new TreeMap();
	private static TreeMap unplayedMatches = new TreeMap();
    private static TreeMap players = new TreeMap();
	private static HashMap rounds = new HashMap();
	private static HashMap pages = new HashMap();
	private static TreeMap leagueAwards = new TreeMap();
	private static TreeMap reports = new TreeMap();
	
	private static int latestMatchId;
	public static void getAll(){
		
		DBAccess db = new DBAccess();
		try{//getLeague();
		getPlayers(db);
		getMatchesList(db);
		getPages(db);
		GrabSeasons.grabLeagueSeasons(db);
		GrabTeams.grabTeams(db);
		GrabReports.grabReports(db);
		
		
		
		}catch(Exception e){
			e.printStackTrace();
		}
		db.disconnect();
		
	}
	

	public static void getMatchesList(DBAccess db){
		try{
		
			ResultSet teamsResult = db.retrieveMatches();
			
			while(teamsResult.next()){
				 try{
			     
					 com.bafa.objects.Match match = (com.bafa.objects.Match)Utils.readBetwixt(new String(teamsResult.getBytes("match")),"match",com.bafa.objects.Match.class);
                     
					 if(match.getID()>latestMatchId)
						 latestMatchId = match.getID();
                            if(!match.isPlayed())
								unplayedMatches.put(match.getID(),match.getID());
                            matches.put(match.getID(), match);
				 }catch(Exception ioe){
			            ioe.printStackTrace();
			        }
				
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
    public static void getPlayers(DBAccess db){
            try{
            
                    ResultSet teamsResult = db.retrievePlayers();
                    
                    while(teamsResult.next()){
                             try{
                         
                           
                          Player player = (Player)Utils.readBetwixt(new String(teamsResult.getBytes("player")),"player",Player.class);
                            players.put(player.getFirstname().toUpperCase(), player);
                             }catch(Exception ioe){
                                ioe.printStackTrace();
                            }
                            
                    }
					
					
            }catch(Exception e){
                    e.printStackTrace();
            }
	
            
    }
	/*
	public static void refreshMatch(int matchId,boolean refreshScorers){
		DBAccess db = new DBAccess();
		try{
			ObjectFactory factory = new ObjectFactory();
			
			QueryObject query3 = new QueryObject(MATCHES);
			query3.addWhereAndField("id", ""+matchId);
			ResultSet rs4 = db.query(query3);
			while(rs4.next()){
				Match match = factory.createMatch();
				XMLGregorianCalendar cal =DatatypeFactory.newInstance().newXMLGregorianCalendar();
				
				if(rs4.getDate(2)!=null){
					cal.setYear(rs4.getDate(2).getYear()+1900);
					cal.setMonth(rs4.getDate(2).getMonth()+1);
					cal.setDay(rs4.getDate(2).getDate());
					match.setDate(cal);
				}
				match.setID(rs4.getInt("ID"));
				match.setAwayAdded((rs4.getInt("AddedB")==1));
				match.setHomeAdded((rs4.getInt("AddedA")==1));
				match.setAwayGoals(rs4.getInt("GoalsB"));
				match.setHomeGoals(rs4.getInt("GoalsA"));
				match.setAwayTeam(rs4.getInt("TeamB"));
				match.setHomeTeam(rs4.getInt("TeamA"));
				match.setBlocked((rs4.getInt("Blocked"))==1);
				match.setTime(rs4.getString("Time"));
				if(match.isAwayAdded()&&match.isHomeAdded())match.setConfirmed(true);
				
				match.setDivision(rs4.getInt("Division"));
				match.setSeasonId(rs4.getInt("SeasonId"));
				match.setPlayed((rs4.getInt("Played"))==1);
				addScorersToMatch(match,db);
				
				//db.updateMatch(match);
				
				if(match.getDivision()>0){
					GrabDivision.grabTeams(RetrieveCache.getSeason(match.getSeasonId()).getDivision().get(match.getDivision()-1),db);
				}
				
				if(refreshScorers){
					GrabDivision.grabDivisionTopScorers(db,RetrieveCache.getSeason(match.getSeasonId()).getDivision().get(match.getDivision()-1));
				}
				matches.put(match.getID(),match);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}
		
	}*/
	/*
	private static void addScorersToMatch(Match match,DBAccess db)throws Exception{
		ObjectFactory factory = new ObjectFactory();
		
		QueryObject query3 = new QueryObject(SCORERS);
		query3.addWhereAndField(SCORERS_MATCHID,new Integer(match.getID()).toString());
		ResultSet rs3 = db.query(query3);
		
		
		while(rs3.next()){
			Scorer scorer = factory.createScorer();
			scorer.setGoals(rs3.getInt("NumberOfGoals"));
			scorer.setName(rs3.getString(SCORERS_SCORERNAME));
			scorer.setTeamId(rs3.getInt(SCORERS_TEAMID));
			if(rs3.getInt(SCORERS_TEAMID)==match.getHomeTeam()){
				match.getHomeScorer().add(scorer);
			}else{
				match.getAwayScorer().add(scorer);
			}
		
		}
	}*/
	
	
	private static void getPages(DBAccess db){
		QueryObject query = new QueryObject("pages");
		try{
			ResultSet rs = db.query(query);
			while(rs.next()){
				PageBean pageBean = new PageBean(rs.getString("id"),rs.getString("LHS"),
												 rs.getString("mainbody"),
												 rs.getString("mainheader"),
												 rs.getString("pageheader"),
												 rs.getString("event"),
												 (rs.getInt("user")==1),
												 (rs.getInt("admin")==1), (rs.getInt("sendemail")==1), rs.getString("email"));
				pages.put(rs.getString("ID"),pageBean);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	public static void refreshAll(){
		//seasons = new TreeMap();
		//matches = new TreeMap();
		getAll();
	}
	
	
	
	public static void main(String[] args) {
		LeagueCache.refreshAll();
		
	}



	public static HashMap getPages() {
		return pages;
	}
	
	
	
	

	public static TreeMap getLeagueAwards() {
		return leagueAwards;
	}

	


	public static TreeMap getMatches() {
		return matches;
	}
	public static void storeMatch(Match match){
            if(matches.containsKey(match.getID())){
                matches.remove(match.getID());
            }
            
            matches.put(match.getID(),match);
        }
        
    public static TreeMap getPlayers() {
            return players;
    }
    public static void storePlayer(Player player){
        if(players.containsKey(player.getFirstname())){
            players.remove(player.getFirstname());
        }
        
        players.put(player.getFirstname(),players);
    }


	public static int getLatestMatchId() {
		return latestMatchId;
	}


	public static void setLatestMatchId(int latestMatchId) {
		LeagueCache.latestMatchId = latestMatchId;
	}


	public static TreeMap getUnplayedMatches() {
		return unplayedMatches;
	}


	public static void setUnplayedMatches(TreeMap unplayedMatches) {
		LeagueCache.unplayedMatches = unplayedMatches;
	}
	
	
}
